def smooth(x,window_len=10,window='hanning'):
    import numpy
    """smooth the data using a window with requested size.
    copied from http://www.scipy.org/Cookbook/SignalSmooth -- Jinbo Wang
    
    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal 
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.
    
    input:
        x: the input signal 
        window_len: the dimension of the smoothing window
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal
        
    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)
    
    see also: 
    
    numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
    scipy.signal.lfilter
 
    TODO: the window parameter could be the window itself if an array instead of a string   
    """

    if x.ndim != 1:
        raise ValueError, "smooth only accepts 1 dimension arrays."

    if x.size < window_len:
        raise ValueError, "Input vector needs to be bigger than window size."

    if window_len<3:
        return x

    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"

    s=numpy.r_[2*x[0]-x[window_len:1:-1],x,2*x[-1]-x[-1:-window_len:-1]]
    #print(len(s))
    if window == 'flat': #moving average
        w=ones(window_len,'d')
    else:
        w=eval('numpy.'+window+'(window_len)')

    y=numpy.convolve(w/w.sum(),s,mode='same')
    return y[window_len-1:-window_len+1]

def cpath(n):
    """Get the path name, goes back n levels
       For example: you are currently in /home/yourname/level1/level2/level3
       cpath(3) will give you /level1/level2/level3/filename
       Strangely, I forgot whether I wrote this, or somebody else did. -- Jinbo Wang
    """
    import os
    import sys
    return reduce(lambda l,r:l+'/'+r, os.getcwd().split('/')[-n:])+'/'+sys.argv[0]

def putpathinfo(n,fig):
    """ Insert the file path info in grey font into the bottom left corner in a figure with
    figure handle 'fig'. The input n is the levels of the path. Nothing fancy,
    just remind yourself which file producted the figure.
    
    For example: putpathinfo(1,fig) will put level1/filename.py into the figure
    with handle 'fig'.
    """
    import os
    import sys
    import pylab
    ax=fig.add_axes([0,0,0.4,0.02])
    ax.set_axis_off()
    txt= reduce(lambda l,r:l+'/'+r,os.getcwd().split('/')[-n:])+sys.argv[0].replace('./','/')
    ax.text(0,0.07,txt,transform=pylab.gca().transAxes,color='grey')

def makemovie(fn,data):
    """
    The famous make movie from png script. You can find everywhere if you search
    matplotlib make movie.
    Input data should be a 3 dimensional array with the 0-th dimension representing
    the time. It produces the movie file fn.mpg
    """
    import os, sys
    import pylab
    files = []
    TimeSteps=data.shape[0]
    for i in range(TimeSteps):
        pylab.clf()
        pylab.pcolor(data[i,:,:])
        fname = '_tmp%03d.png'%i
        print 'Saving frame', fname
        pylab.savefig(fname, dpi=50)
        files.append(fname)
    print 'Making movie animation.mpg - this make take a while'
    os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=5 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o "+fn+".mpg") 

def checkmake(fn):
    """
    Make a folder with name 'fn'.
    """
    import os
    if not os.path.exists(fn):
        os.mkdir(fn)
